# Definition for a binary tree node.
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        str_list = []

        def dfs(root: Optional[TreeNode], prefix: str):
            nonlocal str_list
            cur = prefix + str(root.val)
            if root.left is None and root.right is None:
                str_list.append(cur)
                return
            if root.left:
                dfs(root.left, cur)
            if root.right:
                dfs(root.right, cur)

        dfs(root, "")

        ans = 0
        for s in str_list:
            ans += int(s)
        return ans